using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Event;
using NHibernate.Tool.hbm2ddl;

namespace DAL
{
    class SessionFactory
    {
        public SessionFactory()
        {

        }

        private static ISessionFactory sessions;

        private static Configuration cfg;

        static readonly object padlock = new object();

        public static ISession OpenSession(string AssemblyName)
        {
            if (sessions == null)
            {
                lock (padlock)
                {
                    if (sessions == null)
                    {
                        BuildSessionFactory(AssemblyName);
                        }
                }
            }
            return sessions.OpenSession();
        }

        private static void BuildSessionFactory(string AssemblyName)
        {
            cfg = new Configuration();
            cfg.Configure(System.Configuration.ConfigurationManager.AppSettings["hibernate.cfg.xml"]);
            string connection_string = cfg.GetProperty("connection.connection_string");
            connection_string = connection_string.Replace("|AppDirectory|", Enums.Environment.CurrentDirectory);
            cfg.SetProperty("connection.connection_string", connection_string);
            cfg.AddAssembly(AssemblyName);
            sessions = cfg.BuildSessionFactory();
        }
    }
}
